30

Beginner’s Guide to Code Algorithms

30

End If

Else If Cell 4 =​ “X”

If Cell5 =​ “X”

    If Cell6 =​ “X”

      XScore =​ Win

    End If

End If

:

:

End If

This would be just like the rudimentary 16-​line code we reviewed at the beginning of

this chapter that had several flaws such as being too long and not easily extensible for

a matrix of order greater than 3.

Wouldn’t it be nice to just apply one function to the cell values that tells us this is

a Win for someone? This would potentially reduce the size of the code to one line,

somewhat like this:

Function(X) =​ Win

Knowing that we can do any operation on the cells, we can experiment with a few

choices.

Let’s say we add them up.

15

1

2

3

6

4

5

6

15

7

8

9

22

12

15

18

15

FIGURE 2.27  Unique totals.

The row totals are in yellow, column totals in blue, and diagonal totals in green.

This scheme would not work because the sums are not unique.

If they are not unique, you would not know what combination caused the win, simply

by looking at the score.

A clever way of determining this is to assign prime numbers to each cell. Prime

numbers have the unique property of having only two factors—​1 and the number

itself. Hence if we were to multiply the numbers in a row, column, or diagonal, they

will always yield a unique value.